#ifndef _EVENT_HPP
#define _EVENT_HPP

// #include "wifi.h"

void eventInit();
void eventStart();

void eventInit() {
	eventGroup = xEventGroupCreate();
	if(eventGroup == NULL) {
		printf("Event Group create fail!");
	}
	else {
		xTaskCreatePinnedToCore(eventStart, "eventStart", 1024 * 10, NULL, 0, NULL, 0);
	}
}


void eventStart() {
	EventBits_t bits;
	while(1)
	{
		bits = xEventGroupWaitBits(
			eventGroup,
			EVENT_SCREEN_INIT_DONE |
			EVENT_WIFI_CONNECTED |
			EVENT_WIFI_DISCONNECTED |
			EVENT_WIFI_ESPTOUCH_DONE |
			EVENT_WS_CONNECTED |
			EVENT_WS_DISCONNECTED,
			true,
			false, 
			portMAX_DELAY
		);

		if(bits & EVENT_SCREEN_INIT_DONE) {
			// 初始化页面
			pageInit();
			pageInfoInit();
			pageInfoAdd("Display init done.");
			beeInit();
			
			// 初始化nvs
			nvsInit();
			// 初始化wifi
			xTaskCreatePinnedToCore(wifiInit, "wifiInit", 1024 * 5, NULL, 0, NULL, 0);
			
		}
		if(bits & EVENT_WIFI_CONNECTED) {
			statusBarIconStatus("wifi", true);
			char *ip[16] = {0};
			sprintf((char *)ip, "(%s)", (char *)localIP);
			statusBarIp((char *)ip);
			// 初始化WebSocket
			xTaskCreatePinnedToCore(wsInitTask, "wsInitTask", 1024 * 5, NULL, 0, NULL, 0);
		}
		else if(bits & EVENT_WIFI_DISCONNECTED) {
			statusBarIp("");
			statusBarIconStatus("wifi", false);
		}
		else if(bits & EVENT_WS_CONNECTED) {
			statusBarIconStatus("ws", true);
			// 如果在自检页面，则转到首页
			if(currentPage == PAGE_INFO) {
				vTaskDelay(pdMS_TO_TICKS(300));
				pageHomeInit();
			}
			
			// WebSocket发送操作
			xTaskCreatePinnedToCore(wsSendOp, "wsSendOp", 1024 * 8, NULL, 0, &wsSendOpH, 0);
		}
		else if(bits & EVENT_WS_DISCONNECTED) {
			statusBarIconStatus("ws", false);
		}
	}
}

#endif
